<?php
/**
 * New Post Administration Screen.
 *
 * @package WordPress
 * @subpackage Administration
 */

/** Load WordPress Administration Bootstrap */
require_once( './admin.php' );
require_once('./admin-header.php');
?>

<?php if($_POST['step']=='1'){ ?>
<?php 
include "../wp-config.php";

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME,$con);

$query=mysql_query('select term_id,name from wp_terms');
?>
<?php
/***********************************************
Written By: Jared Elkins
Date:
Function:
***********************************************/

//Set the state of the script;

$youtubeurl=@$_POST['video_url'];
preg_match('#(\.be/|/embed/|/v/|/watch\?v=)([A-Za-z0-9_-]{5,11})#', $youtubeurl, $matches);
if(isset($matches[2]) && $matches[2] != ''){
     $youtubeurl = $matches[2];
}

$debug=1;
$video =$youtubeurl;
ini_set('display_errors',1); 
error_reporting(E_ALL);
$url = 'https://gdata.youtube.com/feeds/api/videos/'.$video.'?v=2';
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	curl_close($ch); 

	$url = 'https://gdata.youtube.com/feeds/api/videos/'.$video.'?v=2&alt=json';
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	curl_close($ch); 
	
	$array = json_decode($output);

	$t='$t';
	$title=$array->entry->title->$t;

	$des='media$description';

	$entry=(array)$array->entry;
	$desarray=(array)$entry['media$group']->$des;
	$description=$desarray['$t'];
	
	$stopwords = array("a", "about", "above", "above", "across", "after", "afterwards", "again", "against", "all", "almost", "alone", "along", "already", "also","although","always","am","among", "amongst", "amoungst", "amount",  "an", "and", "another", "any","anyhow","anyone","anything","anyway", "anywhere", "are", "around", "as",  "at", "back","be","became", "because","become","becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "bill", "both", "bottom","but", "by", "call", "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de", "describe", "detail", "do", "done", "down", "due", "during", "each", "eg", "eight", "either", "eleven","else", "elsewhere", "empty", "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few", "fifteen", "fify", "fill", "find", "fire", "first", "five", "for", "former", "formerly", "forty", "found", "four", "from", "front", "full", "further", "get", "give", "go", "had", "has", "hasnt", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "hundred", "ie", "if", "in", "inc", "indeed", "interest", "into", "is", "it", "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd", "made", "many", "may", "me", "meanwhile", "might", "mill", "mine", "more", "moreover", "most", "mostly", "move", "much", "must", "my", "myself", "name", "namely", "neither", "never", "nevertheless", "next", "nine", "no", "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves", "out", "over", "own","part", "per", "perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed", "seeming", "seems", "serious", "several", "she", "should", "show", "side", "since", "sincere", "six", "sixty", "so", "some", "somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "system", "take", "ten", "than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "thereupon", "these", "they", "thickv", "thin", "third", "this", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", "twelve", "twenty", "two", "un", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what", "whatever", "when", "whence", "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "whoever", "whole", "whom", "whose", "why", "will", "with", "within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves", "the", "over");
	
	
function extract_keywords($str, $minWordLen = 3, $minWordOccurrences = 2, $asArray = false)
{
	
	function keyword_count_sort($first, $sec)
	{
		return $sec[1] - $first[1];
	}
	$str = preg_replace('/[^\p{L}0-9 ]/', ' ', $str);
	$str = trim(preg_replace('/\s+/', ' ', $str));
	
	$words = explode(' ', $str);
	$keywords = array();
	while(($c_word = array_shift($words)) !== null)
	{
		if(strlen($c_word) < $minWordLen) continue;
		
		$c_word = strtolower($c_word);
		if(array_key_exists($c_word, $keywords)) $keywords[$c_word][1]++;
		else $keywords[$c_word] = array($c_word, 1);
	}
	usort($keywords, 'keyword_count_sort');
	
	$final_keywords = array();
	foreach($keywords as $keyword_det)
	{
		if($keyword_det[1] < $minWordOccurrences) break;
		array_push($final_keywords, $keyword_det[0]);
	}
	return $asArray ? $final_keywords : implode(', ', $final_keywords);
}

$description_findkeyword = ($description) ? $description : $title;
$text = $description_findkeyword.', '.$title;
$video_tags=extract_keywords($text);
foreach($stopwords as $key=>$value)
{
	$video_tags=str_replace(' '.$value.',',' ',$video_tags);
}
		
?>
<?php
global $wp_query, $current_user;
    	
    /* Get the current user in the admin */
    $user = new WP_User( $current_user->ID );
            
    /* Get the user role */
    $user_cap = $user->roles;
    
    /* Get the user login name/ID */
    if ( function_exists( 'get_users' ) )
        $user_login = $user->user_nicename;
    elseif ( function_exists( 'get_users_of_blog' ) )
        $user_login = $user->ID;
    
    /* Get selected categories for Roles */
    $settings = get_option( 'RestrictCats_options' );
    
    /* Get selected categories for Users */
    $settings_user = get_option( 'RestrictCats_user_options' );

    $cat_list = "";
    
    /* Selected categories for User overwrites Roles selection */
    if ( is_array( $settings_user ) && !empty( $settings_user[ $user_login . '_user_cats' ] ) ) {
        /* Strip out the placeholder category, which is only used to make sure the checkboxes work */
        $settings_user[ $user_login . '_user_cats' ] = array_values( array_diff( $settings_user[ $user_login . '_user_cats' ], array( 'RestrictCategoriesDefault' ) ) );
        
        /* Build the category list */
        foreach ( $settings_user[ $user_login . '_user_cats' ] as $category ) {
            $term_id = get_term_by( 'slug', $category, 'category' )->term_id;
            
            /* If WPML is installed, return the translated ID */
            if ( function_exists( 'icl_object_id' ) )
                $term_id = icl_object_id( $term_id, 'category', true );
            
            $cat_list .= $term_id . ',';
        }
    }
    else {
        foreach ( $user_cap as $key ) {
            /* Make sure the settings from the DB isn't empty before building the category list */
            if ( is_array( $settings ) && !empty( $settings[ $key . '_cats' ] ) ) {
                /* Strip out the placeholder category, which is only used to make sure the checkboxes work */
                $settings[ $key . '_cats' ] = array_values( array_diff( $settings[ $key . '_cats' ], array( 'RestrictCategoriesDefault' ) ) );
                
                /* Build the category list */
                foreach ( $settings[ $key . '_cats' ] as $category ) {
                    $term_id = get_term_by( 'slug', $category, 'category' )->term_id;
                    
                    /* If WPML is installed, return the translated ID */
                    if ( function_exists( 'icl_object_id' ) )
                        $term_id = icl_object_id( $term_id, 'category', true );
                    
                    $cat_list .= $term_id . ',';
                }
            }
        }
    }
    $cat_list = rtrim( $cat_list, ',' );
    $cat_query_where = "";
    if($cat_list !== '') {
        $cat_query_where = "AND ( t.term_id IN ( $cat_list ) OR tt.taxonomy NOT IN ( 'category' ) ) ";
    }
    $cat_query = mysql_query("  SELECT t.*, tt.* 
                        FROM wp_terms AS t 
                        INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id 
                    WHERE 
                        tt.taxonomy IN ('category') ". $cat_query_where . " ORDER BY t.name ASC");
    
    $result = null;
    
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="step" value="2" />
<input type="hidden" name="vid" value="<?php echo @$video ?>" />
<div style="width:300px;float:left; text-align:left;">
Select a Category</div><div style="float:left;text-align:left;width:300px;">
<select name="cat"><option value="">Select</option>
<?php
while($result=mysql_fetch_array($cat_query))
{?>
	<option value="<?php echo $result['term_id'] ?>"><?php echo $result['name'] ?></option>
<?php }
?>
</select></div>
<br clear="all" />
<div style="height:15px;"></div>
<div style="width:300px;float:left; text-align:left;">Is the title OK?</div>
<div style="width:300px;float:left; text-align:left;">
<input type="text" name="title" value='<?php echo @$title ?>' size="33" />
</div>

<br clear="all" />
<div style="height:15px;"></div>
<div style="width:300px;float:left; text-align:left;">Is the description OK?</div>
<div style="width:300px;float:left; text-align:left;">
<textarea name="description"  rows="10" cols="40"><?php echo @$description ?></textarea></div>

<br clear="all" />
<div style="height:15px;"></div>
<div style="width:300px;float:left; text-align:left;">Tags:</div>
<div style="width:300px;float:left; text-align:left;">
<textarea name="tags"  rows="10" cols="40"><?php echo @$video_tags ?></textarea></div>

<br clear="all" />

<div style="height:15px;"></div>
<div style="width:300px;float:left; text-align:left;">Is this the URL to the video you selected?</div><div style="width:300px;float:left; text-align:left;"><input type="text" name="video_url" size="33" value="<?php echo @$_POST['video_url'] ?>" /></div><br clear="all" /><div style="height:15px;"></div><div style="width:300px;float:left; text-align:left;">Is this the video you selected?</div><div style="width:300px;float:left; text-align:left;"></div>

<?php echo $video_embed= ' <object width="560" height="315"><param name="movie" value="http://www.youtube.com/v/'.$video.'?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'.$video.'?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>'; ?>
<div style="height:15px;"></div>
<div style="width:300px;float:left; text-align:left;">&nbsp;</div><div style="width:300px;float:left; text-align:left;"><input type="submit" name="submit" value="enter" /></div>
</form>


<?php }
if($_POST['step']=='2')
{
$youtubeurl=@$_POST['video_url'];
preg_match('#(\.be/|/embed/|/v/|/watch\?v=)([A-Za-z0-9_-]{5,11})#', $youtubeurl, $matches);
if(isset($matches[2]) && $matches[2] != ''){
     $youtubeurl = $matches[2];
}
$title = @$_POST['title'];
	$video_tags=(string)$_POST['tags'];
	$description=(string)$_POST['description'];
	$video = @$_POST['vid'];

	$video_tags=(string)$_POST['tags'];
	$description=(string)$_POST['description'];
	$video_embed= ' <object width="560" height="315"><param name="movie" value="http://www.youtube.com/v/'.$video.'?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'.$video.'?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>';

 $query="insert into youtube_vids(video_url,video_title,video_description,video_embed,video_tags,wp_category_id) values('".$youtubeurl."','".$title."','".$description."','".$video_embed."','".$video_tags."','".$_POST['cat']."')";
 mysql_query($query);
 
 $id = mysql_insert_id();
 
 require('../wp-load.php');
 
 $caticon = "select * from youtube_vids where vid_id=".$id;
$datacat = $wpdb->get_results($caticon);
foreach ($datacat as $dct) {

$new_post = array(
    'post_title' => $dct->video_title,
    'post_content' => $dct->video_description,
    'post_status' => 'publish',
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => 1,
    'post_type' => 'post',
    'post_category' => array($dct->wp_category_id)
);
$post_id = wp_insert_post($new_post);
if(!wp_is_post_revision($post_id)) {
		add_post_meta($post_id, 'Video',$dct->video_embed, true);
	}
	}
 
 // insert into posts table
/*	$PostCategory = $_POST['cat'];
	$CurrDate = date('Y-m-d H:i:s');
 
   $GetPostIdResource = mysql_fetch_object(mysql_query("SELECT MAX(ID) as Id from wp_posts"));
   $GetPostId = $GetPostIdResource->Id;
   $NewPostId = $GetPostId + 1;
   
   $Postname = str_replace(" ","-",$title);
   
   $Guid = '?'.$CurrDate;
      
  $query_post="insert into wp_posts(ID,post_author,post_date,post_date_gmt,post_content,post_title,post_excerpt,post_status,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_content_filtered,post_parent,guid,menu_order,post_type,post_mime_type,comment_count) values('',1,'".$CurrDate."','".$CurrDate."','".$description."','".$title."','','Publish','open','open','','".$Postname."','','','".$CurrDate."','".$CurrDate."','','',0,'".$Guid."','post','',0)";
  
   mysql_query($query_post);
    
  $query_category = "INSERT INTO wp_term_relationships(object_id,term_taxonomy_id,term_order) VALUES('".$NewPostId."','".$PostCategory."',0)";
	mysql_query($query_category); */
  ?>
<div style="height:50px">&nbsp;</div>
<div align="center"><h3>Add youtube video</h3></div>

<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="step" value="1" />
<div style="width:300px; float:left; text-align:left;">Enter the URL of the video from Youtube</div>
<div style="width:200px; float:left; text-align:left;"><input type="text" name="video_url" /></div><br clear="all" />
<div style="width:500px; text-align:center; margin-left:auto; margin-right:auto;float:left;"><input type="submit" name="submit" value="add" /></div>
</form>
<?php }

if(!isset($_POST['step'])){ ?>

<div style="height:50px">&nbsp;</div>
<div align="center"><h3>Add youtube video</h3></div>

<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="step" value="1" />
<div style="width:300px; float:left; text-align:left;">Enter the URL of the video from Youtube</div>
<div style="width:200px; float:left; text-align:left;"><input type="text" name="video_url" /></div><br clear="all" />
<div style="width:500px; text-align:center; margin-left:auto; margin-right:auto;float:left;"><input type="submit" name="submit" value="add" /></div>
</form>
<?php } ?>
<?php
include('./admin-footer.php');

?>
	